package com.kevin.pay.exception;

import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class CustomExceptionHandlerResolver implements HandlerExceptionResolver {

    @Nullable
    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, @Nullable Object o, Exception exception) {
        //是否为ajax请求
        String requestType = request.getHeader("X-Requested-With");
        if(exception instanceof Exception){
            response.setStatus(413);//无权限异常  主要用于ajax请求返回
            response.addHeader("Error-Json", "{\"code\":413,\"msg\":\"nopermission\"}");
            response.setContentType("text/html;charset=utf-8");
            if("XMLHttpRequest".equals(requestType)){
                return new ModelAndView();
            }
            return new ModelAndView("redirect:/html/413.html");
        }
        return null;
    }
}
